let host = require("./host.js");  // 引入配置文件
const app = getApp();
/**
 * 后台API请求
 * @param {*对象参数} params 
 * @param {*回调函数} callback 
 */
export class Request {
  static HOST = host.default.service.host;
  static LOGIN = 'https://zhiyuzhiying.zyfuns.com/api/';
  
  constructor(url = null, data) {
    this.url = url;
  }
  request(params, callback, header = 'application/x-www-form-urlencoded') {
    let PostParams = new Object();
    for (const key in params()) {
      PostParams[key] = params()[key];
    }
    PostParams['self_site_id'] = app.globalData.self_site_id?app.globalData.self_site_id:self_site_id;
    wx.request({
      url: `${Request.HOST}${this.url}`,
      method: 'POST',
      data: PostParams,
      header: {
        'openid': app.globalData.openid,
        'content-type': header || 'application/x-www-form-urlencoded',
        'cookie': 'PHPSESSID=' + getApp().globalData.phpsessId
      },
      success: (setData) => {
        setData.data.code == -1 || setData.statusCode != 200 ? new error() : new success();

        function success() {
          callback(setData);
        }

        function error() {
          wx.showToast({
            title: '登陆超时',
            icon: 'none',
            duration: 2000,
            mask: true
          });
          setTimeout(function () {
            // wx.redirectTo({
            //   url: '/pages/zhao_home/zhao_home'
            // })
            // wx.navigateBack({
            //   delta: 1
            // })
          }, 2000);
        }
      }
    });
  }

  /**
   * 界面提示
   * @param {*} params 
   * @param {*} callback 
   */
   showToast(title, icon = 'none', setTimeout = Object) {
		wx.showToast({
			title: title,
			icon: icon,
			duration: 1000,
			mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
		});
		//接口报错，延迟跳转首页
		setTimeout();
    return;
	}
  /**
   * 
   * @param {*登陆函数} params 
   * @param {*回调函数} callback 
   */
  login(params,callback){
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url:  `${Request.LOGIN}${this.url}`,
          method: 'POST',
          data: {
            code:res.code
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded',
          },
          success: (setData) =>{
            setData.data.code == -1 || setData.statusCode != 200 ? new error() : new success();

            function success() {
              callback(setData);
            }
            
            function error() {
              wx.showToast({
                title: '登陆超时',
                icon: 'none',
                duration: 2000,
                mask: true
              });
              setTimeout(function () {
                // wx.redirectTo({
                //   url: '/pages/zhao_home/zhao_home'
                // })
                wx.navigateBack({
                  delta: 1
                })
              }, 2000);
            }
          },
        });
      }
    })
  }
  /**
   * 文本内容鉴黄识别
   * @param {*文本内容} params 
   * @param {*回调函数} callback 
   */
  msgSecCheck(params,callback){
    wx.request({
      url: 'https://api.weixin.qq.com/wxa/msg_sec_check',
      method: 'POST',
      data: params(),
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'cookie': 'PHPSESSID=' + this.globalData.phpsessId
      },
      success: (setData) => {
        setData.data.code == -1 || setData.statusCode != 200 || setData.data.errcode == 87014 ? new error() : new success();
        function success() {
          callback(setData);
        }
        function error() {
          wx.showToast({
            title: '内容含有违法违规内容',
            icon: 'none',
            duration: 2000,
            mask: true
          })
          setTimeout(function () {
            wx.navigateBack({
              delta:1
            })
          }, 2000)
        }
      }
    });
  }
}

//登陆判断
export class Login{
  LoginDown(){
    //用户未登陆提示
    new Request().showToast('当前是游客身份','none',()=>{
      setTimeout(()=>{
        wx.showModal({
          title: '提示',
          content: '是否返回注册登陆页面',
          success (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/index/index',
              });
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        });
      },2000);
    });
  }
}

// 选择图片->上传图片
export class ChooseUpload{

  //上传图片接口
  /**
   * count：选择图片数量 默认是1张
   */
  Image(url, formData, callback){
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 不上传图片
        if(url == false){
          callback(res);
          return;
        }
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        const uploadTask = wx.uploadFile({
          url: url,
          filePath: tempFilePaths[0],
          name: 'file',
          formData: formData(),
          success:function(res){
            callback(JSON.parse(res.data), tempFilePaths);
          }.bind(this),
        });
        //监听文件上传
        uploadTask.onProgressUpdate(function(res){
          new Request().showToast(`加载中...${res.progress}%`);
        });
      }.bind(this),
    });
  }
}

// 上传文件接口
export class UploadFiles
{

  File(url, tempFilePaths, callback, name = 'file', formData = Object)
  {
    const uploadTask = wx.uploadFile({
      url: url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'cookie': 'PHPSESSID=' + app.globalData.phpsessId
      },
      filePath: tempFilePaths,
      name: name,
      formData: formData(),
      success:function(res){
        callback(JSON.parse(res.data));
      }.bind(this),
      fail: (res)=>{
        console.log(res);
      }
    });
  }
}
